package com.jackstraw.jack_base.datasource.redis.bean;

import com.jackstraw.jack_base.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import java.util.ArrayList;
import java.util.Collection;

/**
 * CacheManage
 * <p>
 * 用于处理Cache注解
 */
@Slf4j
public class CacheManagerMap implements CacheManager, InitializingBean {


    private RedisRouting redisRouting;


    public CacheManagerMap(RedisRouting redisRouting) {
        this.redisRouting = redisRouting;
    }

    @Override
    public Cache getCache(String name) {
        CacheManager cacheManager = this.getCacheManager();
        if (ObjectUtil.ObjectUtilByLang3.isEmpty(cacheManager)) {
            return null;
        }
        return cacheManager.getCache(name);
    }


    @Override
    public Collection<String> getCacheNames() {
        CacheManager cacheManager = this.getCacheManager();
        if (ObjectUtil.ObjectUtilByLang3.isEmpty(cacheManager)) {
            return new ArrayList<>();
        }
        return cacheManager.getCacheNames();
    }

    private CacheManager getCacheManager() {
        RedisDataSourceTemplate redisDataSourceTemplate = redisRouting.determineTargetEntity();
        return redisDataSourceTemplate.getCacheManager();
    }

    @Override
    public void afterPropertiesSet() {
        //TODO 暂时不需要
        //"NoOpCacheManager", new NoOpCacheManager()
    }

}
